﻿using Barbar.MapReport.Common;
using Barbar.MapReport.HtmlRender.Handlers;
using Barbar.MapReport.HtmlRender.Json;
using Barbar.MapReport.HtmlRender.Operations.ValueIndicators;
using JsonSharp;
using JsonSharp.Collections;
using Microsoft.Practices.EnterpriseLibrary.Validation;

namespace Barbar.MapReport.HtmlRender {
  internal class ValueIndicatorService : MapCallbackService {
    public const string FunctionName = "rptHandleValueIndicators";

    internal override JsonValue ProcessCallback(MapCallbackData callbackData) {
      ValueIndicatorCollection valueIndicators = (ValueIndicatorCollection)GetValue(callbackData);
      ValidationResults results = Validation.Validate<ValueIndicatorCollection>(valueIndicators);
      if (!results.IsValid)
        throw new MapReportValidationException(results);

      if (valueIndicators == null || valueIndicators.Count == 0) {
        return new JsonArrays();
      }

      ValueIndicatorAgregatorCollection agregators = valueIndicators.GetAgregatorCollection(callbackData.GeoBound, callbackData.GooleZoomLevel, callbackData.HandlerUrl);
      ValueIndicatorAgregatorCollectionFactory factory = new ValueIndicatorAgregatorCollectionFactory(agregators, valueIndicators.Properties, callbackData.HandlerUrl);
      return factory.ToJsonObject();
    }

    internal override string JavaScriptFunctionName {
      get { return FunctionName; }
    }
  }
}
